package com.wdhcr.service.imp;


import com.wdhcr.entity.Comment;
import com.wdhcr.repository.CommentRepository;
import com.wdhcr.repository.UserRepository;
import com.wdhcr.service.CommentService;
import com.wdhcr.utils.WxUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/*
 * @description: 评论信息的逻辑业务层
 * @author: wdhcr
 * @dateTime: 2020/4/11 19:05
 */
@Service
public class CommentServiceImpl implements CommentService {

    @Autowired
    private CommentRepository commentRepository;


    @Autowired
    private WxUtil wxUtil;

    @Autowired
    private UserRepository userRepository;


    @Value("${demoUrl}")
    private String demoUrl;

    @Override
    public List<Comment> findCommentListById(Long id) {
        List<Comment> all = commentRepository.findCommentsListById(id);
        setBlogIsNull(all);
        return all;
    }
    private List<Comment> setBlogIsNull(List<Comment> comments){
        for (Comment comment : comments) {
            comment.setBlog(null);
            if (comment.getReplyComments().size() !=0){
                setBlogIsNull(comment.getReplyComments());
            }
        }
        return comments;
    }

    @Override
    public Comment saveComment(Comment comment,String openid) {
        comment.setOpenid(openid);
        Long id = comment.getBlog().getId();
        if (0 == comment.getPid() || null == comment.getPid()){
            String openidAdmin = userRepository.findByid(1l);
            String[] split = openidAdmin.split(",");
            wxUtil.sendTemplateMessage("8bIHzCA_nEXeZze_b4H0OgXsEzkQ0bhKtNo8Jx_W654",
                    "有人评论了你的博客！",
                    split[1],
                    split[0],
                    comment.getContent(),
                    demoUrl+"/#/sBlog?id="+id);
        }else {
            String openid1 = commentRepository.findOpenidById(comment.getPid());
            System.out.println("--------------"+openid1);
            wxUtil.sendTemplateMessage("XaOyTTwhtAfAvgpdNLgo6PtEGHgcPoedf971ZSkQhm8",
                    "有人回复你的评论！",
                    comment.getNickname(),//名字
                    openid1,//给谁发
                    comment.getContent(),
                    demoUrl+"/#/sBlog?id="+id);
        }
        comment.setCreateTime(new Date());
        return commentRepository.save(comment);
    }
}
